import {connect} from 'dva';
import React, {PureComponent} from 'react';
import {Form, Input, Upload, message, Switch, Icon, Select, Radio, Modal} from 'antd';
import styles from './UsercreateModal.less';

const FormItem = Form.Item;
const {Option} = Select;

@connect(state => ({
    user: state.user,
}))
@Form.create()
class UserCreateModal extends PureComponent {
    state = {
        item: {
            name: '',
            sex: true,
            phone: '',
            email: '',
            avatar: '',
            role: 'user',
        },
    }
    handleSubmit = (e) => {
        // this.props.dispatch({
        //     type: 'user/status',
        //     payload: {
        //         status,
        //         items: this.state.selectedRows,
        //     },
        //     callback: () => {
        //         this.setState({
        //             selectedRows: [],
        //         });
        //     },
        // });
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.dispatch({
                    type: 'user/add',
                    payload: values,
                    callback: (result) => {
                        if (result.status) {
                            message.success('添加成功');
                            this.props.form.resetFields();
                            this.handleCancel();
                            this.props.dispatch({
                                type: 'user/fetch',
                            });
                        } else {
                            message.success(result.message);
                        }
                    },
                });
            }
        });
    }
    checkPassword = (rule, value, callback) => {
        const form = this.props.form;
        if (value && value !== form.getFieldValue('password')) {
            callback('两次密码不一致');
        } else {
            callback();
        }
    }
    handleCancel = () => {
        this.props.dispatch({
            type: 'user/changeVisible',
            payload: false,
            callback: () => {
               console.log('回调');
            },
        });
    }
    handleChange = (info) => {
        if (info.file.status === 'done') {
            // Get this url from response in real world.
           console.log(info);
           const avatar = info.file.response.data.url;
           this.state.item.avatar = avatar;
           this.setState({
               item: this.state.item,
           });
           return avatar;
        } else {
            return '';
        }
    }
    checkConfirm = (rule, value, callback) => {
        const form = this.props.form;
        if (value && this.state.confirmDirty) {
            form.validateFields(['confirm'], { force: true });
        }
        callback();
    }
    render() {
        const {getFieldDecorator} = this.props.form;
        const item = this.state.item;
        const {user: { confirmLoading, modalVisible}} = this.props;

        const formItemLayout = {
            labelCol: {
                span: 6,
            },
            wrapperCol: {
                span: 14,
            },
        };
        return (
          <Modal
            onOk={this.handleSubmit}
            confirmLoading={confirmLoading}
            onCancel={this.handleCancel}
            title="添加用户"
            width={800}
            visible={modalVisible}
          >
            <Form onSubmit={this.handleSubmit}>
              <FormItem className={styles.formItem} {...formItemLayout} label="昵称" hasFeedback>
                {getFieldDecorator('name', {
                            initialValue: item.name,
                            rules: [
                                {
                                    required: true,
                                    message: '昵称不能为空',
                                },
                            ],
                        })(<Input />)}
              </FormItem>
              <FormItem className={styles.formItem} {...formItemLayout} label="性别" hasFeedback>
                {getFieldDecorator('sex', {
                            initialValue: item.sex,
                            rules: [
                                {
                                    required: true,
                                    type: 'boolean',
                                },
                            ],
                        })(
                          <Radio.Group>
                            <Radio value>男</Radio>
                            <Radio value={false}>女</Radio>
                          </Radio.Group>
                        )}
              </FormItem>
              <FormItem className={styles.formItem} {...formItemLayout} label="手机" hasFeedback>
                {getFieldDecorator('phone', {
                            initialValue: item.phone,
                            rules: [
                                {
                                    required: true,
                                    pattern: /^1[34578]\d{9}$/,
                                    message: '手机号码不正确',
                                },
                            ],
                        })(<Input />)}
              </FormItem>
              <FormItem className={styles.formItem} {...formItemLayout} label="密码" hasFeedback>
                {getFieldDecorator('password', {
                        initialValue: item.password,
                        rules: [
                            {
                                required: true,
                                message: '密码不能为空',
                            },
                            {
                                validator: this.checkConfirm,
                            },
                        ],
                    })(<Input type="password" />)}
              </FormItem>
              <FormItem className={styles.formItem} {...formItemLayout} label="重复密码" hasFeedback>
                {getFieldDecorator('confirm', {
                        initialValue: item.confirm,
                        rules: [
                            {
                                required: true,
                                message: '重复密码不能为空',
                            },
                            {
                                validator: this.checkPassword,
                            },
                        ],
                    })(<Input type="password" />)}
              </FormItem>
              <FormItem className={styles.formItem} {...formItemLayout} label="邮箱" hasFeedback>
                {getFieldDecorator('email', {
                            initialValue: item.email,
                            rules: [
                                {
                                    required: true,
                                    pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/,
                                    message: '邮箱格式不正确',
                                },
                            ],
                        })(<Input />)}
              </FormItem>
              {/*<FormItem className={styles.formItem} {...formItemLayout} label="用户类型" >*/}
                {/*{getFieldDecorator('role', {*/}
                        {/*initialValue: item.role,*/}
                        {/*rules: [*/}
                            {/*{*/}
                                {/*required: true,*/}
                                {/*message: '用户类型不能为空',*/}
                            {/*},*/}
                        {/*],*/}
                    {/*})(*/}
                      {/*<Select>*/}
                        {/*<Option value="user">普通会员</Option>*/}
                        {/*<Option value="order_admin">订单管理员</Option>*/}
                      {/*</Select>)}*/}
              {/*</FormItem>*/}
                <FormItem className={styles.formItem} {...formItemLayout} label="是否为订单管理员" hasFeedback>
                    {getFieldDecorator('order_admin', {
                        initialValue: 0,
                        rules: [
                            {
                                required: true,

                            },
                        ],
                    })(
                        <Radio.Group>
                            <Radio value={1}>是</Radio>
                            <Radio value={0}>否</Radio>
                        </Radio.Group>
                    )}
                </FormItem>
              <FormItem
                className={styles.formItem}
                {...formItemLayout}
                label="状态"
              >
                {getFieldDecorator('status', {valuePropName: 'checked'})(
                  <Switch />
                        )}
              </FormItem>
              <FormItem
                className={styles.formItem}
                {...formItemLayout}
                label="头像"
              >  {getFieldDecorator('avatar', {getValueFromEvent: this.handleChange})(
                <Upload
                  className={styles.avatarUploader}
                  name="file"
                  showUploadList={false}
                  action={`/api/upload?token=${sessionStorage.getItem('access_token')}`}
                >
                  {
                        item.avatar ?
                          <img src={item.avatar} alt="" className={styles.avatar} /> :
                          <Icon type="plus" className={styles.avatarUploaderTrigger} />
                                }
                </Upload>)}
              </FormItem>
            </Form>
          </Modal>
        );
    }
}


export default Form.create()(UserCreateModal);
